package com.framework;

import java.lang.reflect.Field;

// LengthRule实现
class LengthRule implements ValidationRule {
    private final String field;
    private final int min;
    private final int max;
    
    public LengthRule(String field, int min, int max) {
        this.field = field;
        this.min = min;
        this.max = max;
    }
    
    @Override
    public ValidationResult validate(Object object) {
        try {
            Field f = object.getClass().getDeclaredField(field);
            f.setAccessible(true);
            Object value = f.get(object);
            
            if (value == null) {
                return ValidationResult.valid(); // 空值由RequiredRule处理
            }
            
            if (value instanceof String) {
                String str = (String) value;
                int length = str.length();
                
                if (min > 0 && length < min) {
                    return ValidationResult.invalid(field, "MIN_LENGTH", 
                            field + "长度不能小于" + min + "个字符");
                }
                
                if (max > 0 && length > max) {
                    return ValidationResult.invalid(field, "MAX_LENGTH", 
                            field + "长度不能超过" + max + "个字符");
                }
            }
            
            return ValidationResult.valid();
        } catch (Exception e) {
            return ValidationResult.invalid(field, "SYSTEM_ERROR", "系统错误: " + e.getMessage());
        }
    }
}